# -*- coding: utf-8 -*-
# @Time    : 2022/10/23 15:51
# @Author  : 限量老
from django.shortcuts import render, redirect

from app01 import models
from app01.utils.pagination分页组件 import Pagination
from app01.utils.form_总 import PrettyModelForm, PrettyEditModelForm


def pretty_list(request):
    '''靓号列表'''

    # 创建一些号码:
    # for i in range(100,400):
    #     models.PrettyNum.objects.create(mobile=f'18125963{i}',price=888,level=1,status=1)

    # 筛选条件:
    # q=models.PrettyNum.objects.filter(mobile='15998750555',id=5)
    # print('#',q)
    # data_dict={}
    # q1 = models.PrettyNum.objects.filter(**data_dict)#两星传入空字典:获取全部
    # print('##',q1)
    # q2 = models.PrettyNum.objects.filter(id__gt=5)#{__gt=:大于, __gte=:大于等于, __lt=:小于, __lte=:小于等于, }
    # print('###',q2)
    # q3 = models.PrettyNum.objects.filter(mobile__contains='159')
    # #{__startswith:以什么开关, __startswith:以什么结尾, __contains:包涵什么 }
    # print('####',q3)

    # 搜索
    data_dict = {}
    search_data = request.GET.get('q', '')  # 有就取q,默认为空(取全部)

    data_dict['mobile__contains'] = search_data

    # 分页:
    # 获取数据库中所有数据
    # 'id'以asc排序|| '-id'以desc排序
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by('-level')

    page_object = Pagination(request, queryset, page_size=10, plus=5)

    context = {'search_data': search_data,
               'queryset': page_object.page_queryset,  # 分完页的数据
               'page_string': page_object.html()}  # 生成的页码
    return render(request, 'pretty_list.html', context)


def pretty_add(request):
    '''靓号列表'''
    if request.method == 'GET':
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {'form': form})

    # 获取用户在页面提交的数据
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()  # 校验成功保存到数据库
        return redirect('/pretty/list')  # 跳转

    # 校验不成功,跳转原页面,显示错误信息
    return render(request, 'pretty_add.html', {'form': form})


def pretty_edit(request, nid):
    """编辑用户"""
    row_object = models.PrettyNum.objects.filter(id=nid).first()  # 取得编辑行,获取所在ID
    if request.method == 'GET':
        # 根据ID去数据库获取要编辑的那一行数据
        form = PrettyEditModelForm(instance=row_object)  # 把数据发送到表单中去
        return render(request, 'user_edit.html', {'form': form})

    # 提交后数据处理:
    form = PrettyEditModelForm(data=request.POST, instance=row_object)  # 接收表单提交,更新到这一行
    if form.is_valid():  # 校验成功

        '''如果想要再用户输入以外再增加一些值,可以用:#form.instance.字段名=某个值'''

        form.save()  # 把表单各字段更新到数据库
        return redirect('/pretty/list')
    return render(request, 'pretty_edit.html', {'form': form})  # 如果校验不成功,显示错误信息,重回编辑页面


def pretty_delete(request, nid):
    """删除用户"""

    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list')
